//
//  NetHttp.m
//  weizhuan
//
//  Created by lixun on 13-8-2.
//  Copyright (c) 2013年 lixun. All rights reserved.
//

#import "NetHttp.h"
#import <SystemConfiguration/SystemConfiguration.h>
#include <netdb.h>
#import "UD.h"
#import "NSString+Alert.h"
#import "ASIFormDataRequest.h"
@implementation NetHttp

+ (BOOL) isConnected {
	//创建零地址，0.0.0.0的地址表示查询本机的网络连接状态	
	struct sockaddr_in zeroAddress;
	bzero(&zeroAddress, sizeof(zeroAddress));	
	zeroAddress.sin_len = sizeof(zeroAddress);	
	zeroAddress.sin_family = AF_INET;	
	
	// Recover reachability flags	
	SCNetworkReachabilityRef defaultRouteReachability = SCNetworkReachabilityCreateWithAddress(NULL, (struct sockaddr *)&zeroAddress);	
	SCNetworkReachabilityFlags flags;
	
	//获得连接的标志	
	BOOL didRetrieveFlags = SCNetworkReachabilityGetFlags(defaultRouteReachability, &flags);	
	CFRelease(defaultRouteReachability);
	
	//如果不能获取连接标志，则不能连接网络，直接返回	
	if (!didRetrieveFlags)
	{
		return NO;
	}
	
	//根据获得的连接标志进行判断
	BOOL isReachable = flags & kSCNetworkFlagsReachable;
	BOOL needsConnection = flags & kSCNetworkFlagsConnectionRequired;
	return (isReachable && !needsConnection) ? YES : NO;
}

#pragma mark -
#pragma mark send request
- (NSData *)sendPostRequestWithURLStr:(NSString *)inURLStr andPostStr:(NSString *)inPostStr {
    
    NSURL *url = [NSURL URLWithString:[inURLStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
    
	NSMutableURLRequest  *request = [NSMutableURLRequest requestWithURL:url];
    
    if (inPostStr) {
        [request setHTTPMethod:@"POST"];
    }
	[request setTimeoutInterval:20];
    
    [request setValue:[ASIHTTPRequest defaultUserAgentString] forHTTPHeaderField:@"User-Agent"];
    

    
	[request setCachePolicy:NSURLRequestUseProtocolCachePolicy];
	if (inPostStr) {
		NSString * postStr = [NSString stringWithFormat:@"%@",inPostStr];
        
		NSData *postData = [postStr  dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES];   
		[request setHTTPBody:postData];
        
	}
    
	NSURLConnection *connection = [NSURLConnection connectionWithRequest:request delegate:self];
	if(connection){
		_receivedData = [[NSMutableData data] retain];
	}
	while(!_finished) {
		[[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]];
	}
	return [_receivedData autorelease];

}

- (NSData *)sendGetRequestWithURLStr:(NSString *)inURLStr andQueryStr:(NSString *)inQueryStr andGetStr:(NSString*)inGetStr {   
	NSString *urlStr = inURLStr;
	if (inQueryStr) {
		urlStr = [NSString stringWithFormat:@"%@?%@",inURLStr,inQueryStr];
	}
	urlStr = [urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
	NSURL *url=[NSURL URLWithString:urlStr];
	NSMutableURLRequest *request= [NSMutableURLRequest requestWithURL:url];
	[request setHTTPMethod:@"GET"];   
	[request setTimeoutInterval:20];
    
//    [request setValue:[NSString stringWithFormat:@"Mdongying%@/%@/iOS %@",[[UIDevice currentDevice] systemVersion],[NetUtility gethardware],[NetUtility getsoftware]] forHTTPHeaderField:@"User-Agent"];
    [request setValue:[ASIHTTPRequest defaultUserAgentString] forHTTPHeaderField:@"User-Agent"];

    
	if (inGetStr) {
		NSString * getStr = [NSString stringWithFormat:@"getData=%@",inGetStr];
        //NSStringEncoding enc = CFStringConvertEncodingToNSStringEncoding(kCFStringEncodingISOLatin1);
        //NSData *getData = [getStr dataUsingEncoding:enc];
		NSData *getData = [getStr dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES];
		[request setHTTPBody:getData]; 
	}
	NSURLConnection *connection = [NSURLConnection connectionWithRequest:request delegate:self];
	if(connection) {
		_receivedData = [[NSMutableData data] retain];
	}
	while(!_finished) {
		[[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]];
	}		
	return [_receivedData autorelease];
}

#pragma mark -
#pragma mark NSURLConnectionDelegate
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSHTTPURLResponse *)response {
	[_receivedData setLength:0];
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
	[_receivedData appendData:data];
}

-(void)connection:(NSURLConnection *)connection_ didFailWithError:(NSError *)error_ {
	_receivedData = nil;
	_finished = YES;
//    [@"请检查您的网络或稍后重试" showAlert:@"网络错误"];
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection {	
	_finished = YES;
}

@end
